package com.test.SocketDemo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ${DESCRIPTION}
 *
 * @author muxiaoyu
 * @create 2017/06/08 11:34
 **/
public class RemoteFileServer {
    protected int listenport = 3000;

    public static void main(String[] args) {
        RemoteFileServer remoteFileServer = new RemoteFileServer();
        remoteFileServer.acceptConnection();
    }

    public void acceptConnection() {
        try {
            ServerSocket serverSocket = new ServerSocket(listenport);
            Socket incomingConnection;
            while (true) {
                incomingConnection = serverSocket.accept();
                handleConnection(incomingConnection);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void handleConnection(Socket incomingConnection) {
        try {
            //获取传入client socket的outputstream
            OutputStream outputStream = incomingConnection.getOutputStream();
            //获取传入client socket的inputstream
            InputStream inputStream = incomingConnection.getInputStream();
            //inputstream装饰成为BufferedReader
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            //由reader读取到的file 构造filereader
            //bufferedReader.readLine() 获取的是客户端传来的文件名
            FileReader fileReader = new FileReader(new File(bufferedReader.readLine()));
            //filereader--》BufferedReader
            BufferedReader fileBufferedReader = new BufferedReader(fileReader);
            //由传入socket的outputstream构造输出字符流
            PrintWriter printWriter = new PrintWriter(outputStream);
            String line;
            while ((line = fileBufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            fileReader.close();
            printWriter.close();
            bufferedReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
